/*
 * @Author: lujin49
 * @Date: 2024-12-03 17:53:03
 * @LastEditTime: 2024-12-24 11:25:31
 * @Description: 
 */
chrome.runtime.onMessage.addListener(
    function (message, sender, sendResponse) {
        if (message.action === "sync") {
            (async () => {
                try {
                    await PostMessage(message.data, (code) => {
                        if (code == 200)
                            sendResponse("同步成功完成");
                        else if (code == 401)
                            sendResponse("同步失败: 账号和密码错误");
                        else
                            sendResponse("同步失败,未知错误");
                    });
                } catch (error) {
                    sendResponse("同步失败,服务器有问题");
                }
            })();
            return true;
        }
    }
);


async function PostMessage(message, handler) {
    const myHeaders = new Headers();
    myHeaders.append("Content-Type", "application/json");

    // 获取认证信息
    chrome.storage.sync.get(['server', 'auth'], function (result) {
        if (result.auth) {
            myHeaders.append("Authorization", "Basic " + result.auth);
        }

        const requestOptions = {
            method: "POST",
            headers: myHeaders,
            body: message
        };

        fetch(result.server + "/send", requestOptions)
            .then(response => {
                handler(response.status)
            })
            .catch((error) => {
                handler(404)
            });
    });
}